<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Http\Controllers\Api;


abstract class AbstractController
{
//    #[Inject]
//    protected ContainerInterface $container;
//
//    #[Inject]
//    protected RequestInterface $request;
//
//    #[Inject]
//    protected ResponseInterface $response;

    protected function success(mixed $data = [], string $type = 'json', int $code = 200, string $message = '操作成功.')
    {
        [$className, $methodName] = $this->getClassAndMethod($this->request);
        $class = new \ReflectionClass($className);
        $action = $class->getMethod($methodName);

        //判断请求是否有注解
        $annotation = (new AnnotationReader())->getMethodAnnotation($action, ApiResponse::class);
        if($annotation != null){
            //有注解
            if(is_array($data)){
                $annotationClassName = $annotation->type;
                $annotationClass = new $annotationClassName();
                $data = Target::copyProperties($data,$annotationClass);
            }
        }
        return $this->response->{$type}([
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'time' => time(),
        ]);

    }

    private function getClassAndMethod(ServerRequestInterface $request): array|null
    {
        $name = $request->getAttribute(Dispatched::class)->handler->callback;
        if (!is_string($name)) {
            return $name;
        }

        [$class, $method] = explode('@', $name);

        return [$class, $method];
    }
}
